package com.atbun.eduservice.controller;


import com.atbun.commonutils.R;
import com.atbun.eduservice.entity.EduChapter;
import com.atbun.eduservice.entity.vo.ChapterVo;
import com.atbun.eduservice.service.EduChapterService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-05-06
 */
@RestController
@RequestMapping("/eduservice/chapter")
public class EduChapterController {

    @Autowired
    private EduChapterService eduChapterService;


    //********************************************章节 开始***************************************//
    /**
     * 根据课程id查询章节，小节中的内容，
     * @param courseId
     * @return
     */
    @ApiOperation(value = "嵌套章节数据列表")
    @GetMapping("nestedList/{courseId}")
    public R nestedListByCourseId(
            @ApiParam(name = "courseId", value = "课程ID", required = true)
            @PathVariable String courseId){

        List<ChapterVo> chapterVoList = eduChapterService.nestedList(courseId);
        return R.ok().data("items", chapterVoList);
    }


//    章节的增删改查
    @ApiOperation(value = "新增章节")
    @PostMapping("save")
    public R save(
            @ApiParam(name = "chapterVo", value = "章节对象", required = true)
            @RequestBody EduChapter eduChapter){

        this.eduChapterService.save(eduChapter);
        return R.ok();
    }

    @ApiOperation(value = "根据ID查询章节")
    @GetMapping("{id}")
    public R getById(
            @ApiParam(name = "id", value = "章节ID", required = true)
            @PathVariable String id){

        EduChapter eduChapter = this.eduChapterService.getById(id);
        return R.ok().data("eduChapter", eduChapter);
    }

    @ApiOperation(value = "根据ID修改章节")
    @PutMapping("{id}")
    public R updateById(
            @ApiParam(name = "id", value = "章节ID", required = true)
            @PathVariable String id,

            @ApiParam(name = "chapter", value = "章节对象", required = true)
            @RequestBody EduChapter eduChapter){

        eduChapter.setId(id);
        this.eduChapterService.updateById(eduChapter);
        return R.ok();
    }

    /**
     * 删除章节时，需要判断章节下面是否有小节，如果有，则先删除小节内容。
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID删除章节")
    @DeleteMapping("{id}")
    public R removeById(
            @ApiParam(name = "id", value = "章节ID", required = true)
            @PathVariable String id){

        boolean result = this.eduChapterService.removeChapterById(id);
        if(result){
            return R.ok();
        }else{
            return R.error().message("删除失败");
        }
    }
    //********************************************章节 结束***************************************//
}

